<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>生成验证码并且验证</title>
  <style>
      a {
          text-decoration: none;
          color: #487ca0;
      }

      .v-code {
          width: 300px;
          height: 300px;
          background-color: #fff;
          border: 1px solid #ccc;

      }

      .code {
          font-size: 30px;
          color: #000adf;
          font-weight: bolder;
          background-color: #ddd;

      }

      #inputCode {
          width: 100px;
          height: 30px;
          border: 1px solid #ccc;
      }

      #Button1 {
          width: 70px;
          height: 50px;
          border: 1px solid #ccc;

      }


  </style>
</head>
<body>
<div class="v-code">
  <div class="code-show">
    <span class="code" id="checkCode"><em>adf34y</em></span>
    <a href="javascript:;" id="linkbt">看不清换一张</a>
  </div>
  <div class="input-code">
    <label for="inputCode">验证码:</label>
    <input id="inputCode" type="text"/>
    <span id="text-show"></span>
  </div>
  <input id="Button1" type="button" value="确定">
</div>
</body>
<script>
  // 1、生成验证，必须是 0-9，a-z的字符串
  let code
  let codeShow = document.getElementById('checkCode')
  let linkbt = document.getElementById('linkbt')
  let inputCode = document.getElementById('inputCode')
  let textShow = document.getElementById('text-show')
  let Button1 = document.getElementById('Button1')

  function getCode() {
    let codeArr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    code = ''
    for (let i = 0; i < 6; i++) {
      let index = Math.floor(Math.random() * codeArr.length)
      code += codeArr[index]
    }
    return code
  }

  window.onload = function () {
    codeShow.innerHTML = getCode()
  }

  // 2、点击换一张，重新生成验证码
  linkbt.onclick = function () {
    codeShow.innerHTML = getCode()
  }

  // 3、输入验证码，点击确定，验证是否正确
  Button1.onclick = function () {
    if (inputCode.value === '') {
      textShow.innerHTML = `<span style="color:orange">请输入验证码</span>`
      return
    }
    if (inputCode.value === code) {
      textShow.innerHTML = `<span style="color:green">验证成功</span>`
    } else {
      textShow.innerHTML = `<span style="color:red">验证失败</span>`
      codeShow.innerHTML = getCode()
    }
  }


</script>
</html>